package com.cg.design.graphicdesignpattern.flyweight;

/**
 * 表示由多个BigChar组成的“大型字符串”的类
 *
 * @program: LeetCode->BigString
 * @description: 表示由多个BigChar组成的“大型字符串”的类
 * @author: cg
 * @create: 2022-04-03 16:40
 **/
public class BigString {
    /**
     * “大型字符”的数组
     */
    private BigChar[] bigChars;

    /**
     * 构造函数
     * 默认使用共享函数
     *
     * @param string
     */
    public BigString(String string) {
        this(string, true);
    }

    /**
     * 构造函数
     * @param string
     * @param shared 是否使用共享方式
     */
    public BigString(String string, boolean shared) {
        if (shared) {
            initShared(string);
        } else {
            initUnShared(string);
        }
    }

    /**
     * 共享方式初始化
     * @param string
     */
    private void initShared(String string) {
        bigChars = new BigChar[string.length()];
        BigCharFactory factory = BigCharFactory.getInstance();
        for (int i = 0; i < bigChars.length; i++) {
            bigChars[i] = factory.getBigChar(string.charAt(i));
        }
    }

    /**
     * 非共享方式初始化
     * @param string
     */
    private void initUnShared(String string) {
        bigChars = new BigChar[string.length()];
        BigCharFactory factory = BigCharFactory.getInstance();
        for (int i = 0; i < bigChars.length; i++) {
            bigChars[i] = new BigChar(string.charAt(i));
        }
    }

    /**
     * 显示
     */
    public void print() {
        for (BigChar bigChar : bigChars) {
            bigChar.print();
        }
    }

}
